package com.crm.common.handler;

import com.crm.common.constant.ExceptionConstant;
import com.crm.common.exception.BusinessException;
import com.crm.common.result.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 *  全局异常处理器
 * @version 2024/7/19 11:39
**/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获异常
     * @param ex    异常
     * @return      异常信息
     */
    @ExceptionHandler
    public ResultVO<String> exceptionHandler(BusinessException ex){
        log.error("异常信息：{}", ex.getMessage());
        return ResultVO.error(ex.getMessage());
    }

    /**
     * 处理SQL异常
     * @param ex    异常
     * @return      异常信息
     */
    @ExceptionHandler
    public ResultVO<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + ExceptionConstant.ALREADY_EXISTS;
            return ResultVO.error(msg);
        }else{
            return ResultVO.error(ExceptionConstant.UNKNOWN_ERROR);
        }
    }

    // 处理文件大小超限异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxSizeException(MaxUploadSizeExceededException exc) {
        return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
                .body("文件大小超过限制！");
    }

    // 处理其他通用异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception exc) {
        return ResponseEntity.internalServerError()
                .body("服务器内部错误: " + exc.getMessage());
    }
}
